<template>
    <div class="matching-container">
        <div class="matching-card">
            <div class="matching-header">
                <h1>多人匹配 (3人)</h1>
            </div>

            <div class="matching-content">
                <h2>
                    {{
                        isMatching
                            ? matchedPlayers.length === 3
                                ? '匹配成功！'
                                : '正在寻找对手...'
                            : '等待开始匹配'
                    }}
                </h2>

                <div class="players-container">
                    <!-- 已匹配的玩家 -->
                    <div v-for="player in matchedPlayers" :key="player.userId" class="player-card">
                        <div class="player-avatar">
                            <img :src="player.photo" alt="玩家头像" />
                        </div>
                        <div class="player-info">
                            <div class="player-name">{{ player.username }}</div>
                            <div class="player-rating">段位分: {{ player.rating }}</div>
                        </div>
                    </div>

                    <!-- 等待位置 -->
                    <div
                        v-for="i in 3 - matchedPlayers.length"
                        :key="`empty-${i}`"
                        class="player-card empty"
                    >
                        <div class="player-avatar empty-avatar">
                            <el-icon v-if="isMatching" class="loading-icon">
                                <Loading />
                            </el-icon>
                            <span v-else class="player-placeholder">?</span>
                        </div>
                        <div class="player-info">
                            <div class="player-name">
                                {{ isMatching ? '等待玩家加入...' : '等待开始匹配' }}
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="matching-footer">
                <button class="back-btn" @click="goBack">
                    <el-icon>
                        <Back />
                    </el-icon>
                    返回
                </button>

                <button v-if="!isMatching" class="start-btn" @click="startMatching">
                    开始匹配
                </button>

                <button v-else class="cancel-btn" @click="cancelMatching">取消匹配</button>
            </div>
        </div>
    </div>
</template>

<script setup>
    import { onMounted, ref } from 'vue'
    import { useRouter } from 'vue-router'
    import { useUserStore } from '@/stores/user'
    import { useWebsocketStore } from '@/stores/websocket'
    import { ElMessage } from 'element-plus'
    import { Back, Loading } from '@element-plus/icons-vue'

    const router = useRouter()
    const userStore = useUserStore()
    const websocketStore = useWebsocketStore()
    const matchedPlayers = ref([])
    const isMatching = ref(false)

    // 当前玩家信息
    const currentPlayer = {
        userId: userStore.id,
        username: userStore.username,
        photo: userStore.photo,
        rating: userStore.rating,
    }

    // 监听匹配事件
    const setupSocketListener = () => {
        websocketStore.socket.onmessage = (message) => {
            const data = JSON.parse(message.data)
            console.log('收到消息:', data)

            if (data.event === 'matching-success') {
                const opponents = data.opponents
                opponents.forEach((opponent) => {
                    matchedPlayers.value.push(opponent)
                })

                if (data.opponents) {
                    websocketStore.updateOpponents(data.opponents)
                    console.log('opponents: ', data.opponents)
                }

                // 保存房间ID
                if (data.roomId) {
                    websocketStore.updateRoomId(data.roomId)
                    console.log('房间ID:', data.roomId)
                }

                console.log('matchedPlayers: ', matchedPlayers.value)

                if (matchedPlayers.value.length === 3) {
                    // 匹配成功后自动进入游戏
                    enterGame()
                }
            }
        }
    }

    // 组件挂载时加载当前用户信息
    onMounted(() => {
        // 初始化时，第一个槽位显示当前用户
        matchedPlayers.value = [currentPlayer]

        setupSocketListener()
    })

    // 返回上一页
    const goBack = () => {
        router.go(-1)
    }

    // 开始匹配逻辑
    const startMatching = () => {
        if (isMatching.value) return

        isMatching.value = true

        // 重置玩家列表，但确保当前用户在第一位
        matchedPlayers.value = [currentPlayer]

        // 发送开始匹配消息
        if (websocketStore.socket) {
            websocketStore.socket.send(JSON.stringify({ event: 'start-matching' }))
        } else {
            ElMessage.error('网络连接失败，请刷新页面重试')
            isMatching.value = false
        }
    }

    // 取消匹配
    const cancelMatching = () => {
        if (!isMatching.value) return

        isMatching.value = false
        // 取消匹配但保留当前用户头像
        matchedPlayers.value = [currentPlayer]

        // 发送开始匹配消息
        if (websocketStore.socket) {
            websocketStore.socket.send(JSON.stringify({ event: 'stop-matching' }))
        } else {
            ElMessage.error('网络连接失败，请刷新页面重试')
            return
        }

        ElMessage.info('已取消匹配')
    }

    // 开始游戏
    const enterGame = () => {
        // 保存对手信息到websocketStore.pk.opponents
        const opponents = matchedPlayers.value.filter((player) => player.userId !== userStore.id)
        websocketStore.updateOpponents(opponents)

        ElMessage.success('所有玩家已准备就绪，进入游戏！')

        // 延迟1秒后切换状态
        setTimeout(() => {
            websocketStore.updateStatus('playing')
            console.log('进入游戏')
        }, 1000)
    }
</script>

<style scoped>
    .matching-container {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;
        width: 100vw;
        background-color: rgba(0, 0, 0, 0.85);
    }

    .matching-card {
        width: 800px;
        background-color: rgba(0, 0, 0, 0.7);
        border-radius: 12px;
        padding: 30px;
        box-shadow: 0 0 30px rgba(255, 215, 0, 0.3);
        border: 1px solid rgba(255, 215, 0, 0.3);
        color: #fff;
        animation: fadeIn 0.5s ease-in-out;
    }

    .matching-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 30px;
        border-bottom: 1px solid rgba(255, 215, 0, 0.3);
        padding-bottom: 15px;
    }

    .matching-header h1 {
        font-size: 28px;
        color: #ffd700;
        text-shadow: 0 0 10px rgba(255, 215, 0, 0.5);
        margin: 0;
    }

    .matching-content {
        text-align: center;
        margin-bottom: 30px;
    }

    .matching-content h2 {
        color: #ffd700;
        margin-bottom: 20px;
        font-size: 24px;
    }

    .players-container {
        display: flex;
        justify-content: center;
        gap: 30px;
        margin: 30px 0;
    }

    .player-card {
        width: 180px;
        background-color: rgba(255, 255, 255, 0.1);
        border-radius: 10px;
        padding: 20px;
        text-align: center;
        transition: all 0.3s;
    }

    .player-card:not(.empty) {
        animation: pulseAnimation 2s infinite;
    }

    .player-card.empty {
        opacity: 0.6;
    }

    .player-avatar {
        width: 100px;
        height: 100px;
        margin: 0 auto 15px;
        border-radius: 50%;
        overflow: hidden;
        border: 3px solid #ffd700;
    }

    .player-avatar img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .empty-avatar {
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: rgba(255, 255, 255, 0.05);
    }

    .loading-icon {
        font-size: 40px;
        color: #ffd700;
        animation: spin 2s infinite linear;
    }

    .player-placeholder {
        font-size: 40px;
        color: rgba(255, 215, 0, 0.3);
        font-weight: bold;
    }

    .player-info {
        margin-top: 10px;
    }

    .player-name {
        font-size: 18px;
        font-weight: bold;
        margin-bottom: 5px;
    }

    .player-rating {
        font-size: 14px;
        color: #ffd700;
    }

    .matching-footer {
        display: flex;
        justify-content: space-between;
        margin-top: 20px;
        padding-top: 20px;
        border-top: 1px solid rgba(255, 215, 0, 0.3);
    }

    .back-btn,
    .cancel-btn,
    .start-btn {
        padding: 12px 25px;
        border-radius: 6px;
        font-size: 16px;
        font-weight: bold;
        border: none;
        cursor: pointer;
        transition: all 0.3s;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .back-btn {
        background-color: rgba(255, 255, 255, 0.1);
        color: white;
        border: 1px solid rgba(255, 215, 0, 0.3);
    }

    .back-btn:hover {
        background-color: rgba(255, 255, 255, 0.2);
    }

    .cancel-btn {
        background-color: #d32f2f;
        color: white;
    }

    .cancel-btn:hover {
        background-color: #b71c1c;
    }

    .start-btn {
        background-color: #ffd700;
        color: #000;
    }

    .start-btn:hover {
        background-color: #ffc000;
        box-shadow: 0 0 15px rgba(255, 215, 0, 0.5);
    }

    @keyframes fadeIn {
        from {
            opacity: 0;
            transform: translateY(-20px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    @keyframes spin {
        from {
            transform: rotate(0deg);
        }
        to {
            transform: rotate(360deg);
        }
    }

    @keyframes pulseAnimation {
        0% {
            box-shadow: 0 0 0 0 rgba(255, 215, 0, 0.4);
        }
        70% {
            box-shadow: 0 0 0 10px rgba(255, 215, 0, 0);
        }
        100% {
            box-shadow: 0 0 0 0 rgba(255, 215, 0, 0);
        }
    }

    @keyframes pulseAnimationEmpty {
        0% {
            box-shadow: 0 0 0 0 rgba(255, 255, 255, 0.2);
        }
        70% {
            box-shadow: 0 0 0 10px rgba(255, 255, 255, 0);
        }
        100% {
            box-shadow: 0 0 0 0 rgba(255, 255, 255, 0);
        }
    }
</style>
